package com.offcn.question.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.offcn.common.utils.PageUtils;
import com.offcn.common.utils.Query;
import com.offcn.question.dao.QuestionDao;
import com.offcn.question.entity.QuestionEntity;
import com.offcn.question.service.QuestionService;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("questionService")
public class QuestionServiceImpl extends ServiceImpl<QuestionDao, QuestionEntity> implements QuestionService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //创建一个查询条件封装对象
        QueryWrapper<QuestionEntity> queryWrapper = new QueryWrapper<>();
        //尝试获取前端传递查询条件
      String key= (String) params.get("key");
      //获取从前端传递过来的题目分类编号数据
    String typeId= (String) params.get("typeId");
      //判断key是否为空
        if(!StringUtils.isEmpty(key)){
            //设置查询条件
            queryWrapper.like("title",key).or().eq("id",key);
        }

        //判断分类编号数据是否为空
        if(!StringUtils.isEmpty(typeId)){
            //设置按照题目分类查询
            queryWrapper.eq("type",typeId);
        }
        IPage<QuestionEntity> page = this.page(
                new Query<QuestionEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 导入方法
     *
     * @param file 是springboot封装上传文件对象
     * @return 返回结果封装
     */
    @Override
    public Map importExcel(MultipartFile file) {
        //创建map返回封装数据
        Map result=new HashMap<>();
        //获取上传文件原始名称
        String originalFilename = file.getOriginalFilename();
        //获取文件扩展名  .xls  .xlsx  .txt  .c .java
        String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //判断文件扩展名是否是excel的 .xls  .xlsx
        if(!extName.equals("xls")&&!extName.equals("xlsx")){
            result.put("result",false);
            result.put("msg","文件扩展名不正确，导入失败");
            result.put("num",0);//如果导入成功，成功数据条数
            return result;
        }

        try {
            //如果扩展名正确，创建工作簿对象
            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            //获取工作表 导入模板要求工作表名称是固定
            Sheet sheet = workbook.getSheetAt(0);
            //获取行数
            int rowNum = sheet.getPhysicalNumberOfRows();

            for (int i = 1; i < rowNum; i++) {

                //读取每行内容
                Row row = sheet.getRow(i);
                //创建题目实体对象
                QuestionEntity questionEntity = new QuestionEntity();

                //获取每行里面各个单元格
                String title = row.getCell(0).getStringCellValue();
                questionEntity.setTitle(title);

                //设置题目答案
                questionEntity.setAnswer(row.getCell(1).getStringCellValue());
                //设置题目难度等级
                double level = row.getCell(2).getNumericCellValue();
                questionEntity.setLevel((int)level);

                //设置排序
                double displayOrder = row.getCell(3).getNumericCellValue();
                questionEntity.setDisplayOrder((int)displayOrder);

                //副标题

                questionEntity.setSubTitle(row.getCell(4).getStringCellValue());
                //题目类型
                double type = row.getCell(5).getNumericCellValue();
                questionEntity.setType((long)type);

                //是否显示
                double enable = row.getCell(6).getNumericCellValue();
                questionEntity.setEnable((int)enable);

                //调用数据库保存接口
                this.save(questionEntity);
            }

            //准备响应数据
            result.put("result",true);
            result.put("msg","导入成功");
            result.put("num",rowNum-1);//如果导入成功，成功数据条数

        } catch (IOException e) {
            e.printStackTrace();
            result.put("result",false);
            result.put("msg","获取上传文件失败");
            result.put("num",0);//如果导入成功，成功数据条数
        } catch (InvalidFormatException e) {
            e.printStackTrace();
            result.put("result",false);
            result.put("msg","获取导入文件数据失败");
            result.put("num",0);//如果导入成功，成功数据条数
        }

        return result;
    }

    @Override
    public Workbook exportExcel() {
        //创建工作簿对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建一个工作表
        HSSFSheet sheet = workbook.createSheet("导出数据工作表");

        //创建第一行对象，标题栏
        HSSFRow row1 = sheet.createRow(0);

        //设置第一行的标题单元格
        row1.createCell(0).setCellValue("题目标题");
        row1.createCell(1).setCellValue("题目解答");
        row1.createCell(2).setCellValue("题目难度等级");
        row1.createCell(3).setCellValue("排序");
        row1.createCell(4).setCellValue("副标题");
        row1.createCell(5).setCellValue("题目类型");
        row1.createCell(6).setCellValue("是否显示");

        //读取全部题目数据
        List<QuestionEntity> questionEntityList = this.list();
        int rowNum=1;
        //循环遍历题目数据集合
        for (QuestionEntity qs : questionEntityList) {
            //在工作表创建行
            HSSFRow row = sheet.createRow(rowNum);

            //设置每行数据内容
            row.createCell(0).setCellValue(qs.getTitle());
            row.createCell(1).setCellValue(qs.getAnswer());
            row.createCell(2).setCellValue(qs.getLevel());
            row.createCell(3).setCellValue(qs.getDisplayOrder());
            row.createCell(4).setCellValue(qs.getSubTitle());
            row.createCell(5).setCellValue(qs.getType());
            row.createCell(6).setCellValue(qs.getEnable());

            //把行号累加1
            rowNum++;
        }

        return workbook;
    }

    @Override
    public List<Map<String, Object>> countTypeQuestion() {
        //创建查询条件封装对象
        QueryWrapper<QuestionEntity> queryWrapper = new QueryWrapper<>();
        //设置分组条件
        queryWrapper.groupBy("type");
        //设置select 选择列
        queryWrapper.select("type","count(type) as num");

        //发出查询
        return this.baseMapper.selectMaps(queryWrapper);
    }
}